import React, { useState, useEffect } from "react";
import { connect, useDispatch } from "react-redux";
import { Button } from "bigbear-ui";
import NavHeader from "@/components/Nav";
import { getLesson } from "@/api/home";
import { RouteComponentProps } from "react-router";
import { Lesson, LessonResult } from "@/store/reducers/home";
import { StaticContext } from "react-router";
import actions from "@/store/actions/cart";
interface Params {
	id: string;
}
type RouteProps = RouteComponentProps<Params, StaticContext, Lesson>;
type Props = RouteProps & {
	children?: any;
};

function Detail(props: Props) {
	let [lesson, setLesson] = useState<Lesson>({} as Lesson);
	const dispatch = useDispatch();
	useEffect(() => {
		(async () => {
			let lesson: Lesson = props.location.state;
			if (!lesson) {
				let id = props.match.params.id;
				let result: LessonResult = await getLesson<LessonResult>(id);
				if (result.success) lesson = result.data;
			}
			setLesson(lesson);
		})();
	}, [props.location.state, props.match.params.id]);
	const addCartItem = (lesson: Lesson) => {
		dispatch(actions.addCartItem(lesson));
	};
	return (
		<>
			<NavHeader history={props.history}>课程详情</NavHeader>
			<div style={{ width: "100%" }}>
				<video style={{ width: "100%" }} src={lesson.video} controls autoPlay={false} />
			</div>
			<div className="bigbear-layout-block-default" style={{ padding: "10px" }}>
				<div style={{ fontSize: "0.6rem", fontWeight: 700, marginBottom: "0.5rem" }}>
					{lesson.title}
				</div>
				<div
					style={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						fontSize: "0.3rem",
						fontWeight: 700,
						marginBottom: "0.5rem",
					}}
				>
					<span>{`价格: ${lesson.price}`}</span>
					<Button
						btnType="danger"
						className="add-cart"
						onClick={() => addCartItem(lesson)}
					>
						加入购物车
					</Button>
				</div>
			</div>
		</>
	);
}

export default connect()(Detail);
